import os

import pygame
from pygame.locals import *

# Enable import from subdirectories.
os.sys.path.append(os.path.join(os.getcwd(),"objects"))
os.sys.path.append(os.path.join(os.getcwd(),"levels"))

import globalvars       # Import global variables.
import cursor
import panel
import demo             # Import demonstation level.
import tux1

pygame.init()

screen = pygame.display.set_mode(globalvars.resolution) #[1024, 768], pygame.FULLSCREEN (| pygame.HWSURFACE)
pygame.display.set_caption("ArcticArmy")

backgroundImage = os.path.join('data', "snowbg.png")
background = pygame.image.load(backgroundImage).convert()

screen.blit(background, [0, 0])
pygame.display.update()

pygame.mouse.set_visible(True)
cursor = cursor.Cursor()
globalvars.objects_draw.add(cursor)
#Cursor.create(Tux.Tux())

# Create a panel.
panel = panel.Panel("main", "panel.png")
globalvars.objects_panel_draw.add(panel)
panel.add_text()

# Create the loaded level.
level = demo.Level() # TODO: Deside if this should be Global variable and how objects interact with it.


while True:
    # Clear all objects from the screen.
    globalvars.objects_draw.clear(screen, background)
    globalvars.objects_panel_draw.clear(screen, background)
    # TODO: Don't clear an redraw none moving objects if the don't collide with any moving objects.

    # Update the level.
    level.update()

    # Update the objects' positions.
    globalvars.objects_draw.update()
    globalvars.objects_panel_draw.update()

    # Redraw the objects.
    dirtyRects = globalvars.objects_draw.draw(screen)
    # Redraw the panel. It has to be done sperately and after the objects because the panel has to stay on top
    dirtyRects += globalvars.objects_panel_draw.draw(screen)

    # Update the screen where it's needed.
    pygame.display.update(dirtyRects)
    

    # Handle events.
    for event in pygame.event.get():
        if event.type == QUIT:
            exit(0)
        elif event.type == KEYDOWN and event.key == K_ESCAPE:
            exit(0)
        elif event.type == KEYDOWN and event.key == K_1:
            if globalvars.number_of_tuxs >= 1:
                cursor.create(tux1.Tux1())
                #Globals.ObjectsExists.add(Tux.Tux())
                #Globals.NumberOfTuxs -= 1
        elif event.type == KEYDOWN and event.key == K_2:
            if globalvars.number_of_tuxs >= 1:
                cursor.create(tux.Tux())
        elif event.type == MOUSEBUTTONDOWN and event.button == 1:
            cursor.click_left(event.pos)
        elif event.type == MOUSEBUTTONDOWN and event.button == 3:
            cursor.click_right(event.pos)
            
    globalvars.clock.tick(50)

